package com.dongdongshop.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.dongdongshop.pojo.TbGoods;
import com.dongdongshop.pojo.TbGoodsDesc;
import com.dongdongshop.pojo.TbItem;
import com.dongdongshop.service.FreemarkerService;
import com.dongdongshop.service.GoodsDescService;
import com.dongdongshop.service.GoodsService;
import com.dongdongshop.service.ItemService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@org.springframework.stereotype.Service
public class FreemarkerServiceImpl implements FreemarkerService {

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;
    @Reference
    private GoodsService goodsService;
    @Reference
    private GoodsDescService goodsDescService;
    @Reference
    private ItemService itemService;

    @Override
    public void createPage(Long goodsId) {
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        FileWriter writer = null;
        try {
            Template template = configuration.getTemplate("item.ftl");
            Map map = new HashMap();

            writer = new FileWriter("D:\\freemarker\\"+goodsId+".html");
            //根据goodsId 查询商品信息
            TbGoods tbGoods = goodsService.selectByGoodsId(goodsId);
            //根据goodsId 查询商品详情信息
            TbGoodsDesc tbGoodsDesc = goodsDescService.selectGoodsDescByGoodsId(goodsId);
            List<TbItem> itemList = itemService.selectItemListByGoodsId(goodsId);

            map.put("goods",tbGoods);
            map.put("tbGoodsDesc",tbGoodsDesc);
            map.put("itemList",itemList);

            //生成页面
            template.process(map,writer);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if (writer != null){
                    writer.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
